package com.base.cn.platform.os.service.user.account;

import com.base.cn.platform.os.common.msg.WXTmpEnum;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.user.AccountBizType;
import com.base.cn.platform.os.common.utils.user.AccountHistoryType;
import com.base.cn.platform.os.dao.user.account.CusUserAccountHistoryDao;
import com.base.cn.platform.os.entity.order.order.Order;
import com.base.cn.platform.os.entity.user.account.CusUserAccount;
import com.base.cn.platform.os.entity.user.account.CusUserAccountHistory;
import com.base.cn.platform.os.entity.user.account.CusUserAccountHistoryColumns;
import com.base.cn.platform.os.service.manage.user.SysUserBiz;
import com.base.cn.platform.os.service.op.affiche.tmp.SendMessage;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class CusUserAccountHistoryBiz extends BaseBiz<CusUserAccountHistory,CusUserAccountHistoryDao> {

    @Autowired
    private SysUserBiz sysUserBiz;
    @Autowired
    private SendMessage sendMessage;
    /**
     * 添加消费记录,（仅用于后台管理操作用户账户产生的账户变更历史记录）
     * @param userAccount 账户属性对象
     * @param type 操作类型
     * @param amount 操作金额
     */
    public CusUserAccountHistory addUserAccountHistory(BigDecimal createUserId, CusUserAccount userAccount, int type, BigDecimal amount, Order order){
        CusUserAccountHistory userAccountHistory = new CusUserAccountHistory();
        userAccountHistory.setUserId(userAccount.getUserId());
        userAccountHistory.setAccountId(userAccount.getId());
        userAccountHistory.setIsDisplay(1);
        userAccountHistory.setBalance(userAccount.getBalance());
        userAccountHistory.setCashAmount(userAccount.getCashAmount());
        userAccountHistory.setCashForzenAmount(userAccountHistory.getCashForzenAmount());
        userAccountHistory.setVmAmount(userAccount.getVmAmount());
        userAccountHistory.setVmForzenAmount(userAccount.getVmForzenAmount());
        userAccountHistory.setTrxAmount(amount);
        userAccountHistory.setBizType(AccountBizType.ADMIN.getValue());//后台操作
        String description="";
        DecimalFormat nf = new DecimalFormat();
        nf.setMaximumFractionDigits(2);
        // type=1银行充值，type=2银行冻结金额,type=3银行解冻金额
        // type=4充值卡入账,type=5充值卡冻结金额,type=6充值卡解冻金额
        // type=7银行扣款，type=8充值卡扣款
        // type=9银行退款，type=10充值卡退款
        //type=11积分兑换
        if(type==1 || type==4){//后台充值
            if(type==1){
                description="银行充值金额:"+nf.format(amount);
            }
            if(type==4){
                description="充值卡充值金额:"+nf.format(amount);
            }
            userAccountHistory.setActHistoryType(AccountHistoryType.ADMINLOAD.getValue());
        }else if(type==2 || type==5){//后台冻结
            if(type==2){
                description="银行金额冻结:"+nf.format(amount);
            }
            if(type==5){
                description="充值卡金额冻结:"+nf.format(amount);
            }
            userAccountHistory.setActHistoryType(AccountHistoryType.FORZEN_AMOUNT.getValue());
        }else if(type==3 || type==6){//后台解冻
            if(type==3){
                description="银行卡金额解冻:"+nf.format(amount);
            }
            if(type==6){
                description="充值卡金额解冻:"+nf.format(amount);
            }
            userAccountHistory.setActHistoryType(AccountHistoryType.THAW_AMOUNT.getValue());
        }else if(type==7 || type==8){//后台扣款
            if(type==7){
                description="银行卡金额扣款:"+nf.format(amount);
            }
            if(type==8){
                description="充值卡金额扣款:"+nf.format(amount);
            }
            userAccountHistory.setActHistoryType(AccountHistoryType.ADMINREFUND.getValue());
        }
        else if(type==9 || type==10){//后台退款
            if(type==9){
                description="银行卡金额退款:"+nf.format(amount);
            }
            if(type==10){
                description="充值卡金额退款:"+nf.format(amount);
            }
            userAccountHistory.setActHistoryType(AccountHistoryType.REFUND.getValue());
        }else if(type==11){
                 //积分兑换
                description="积分兑换:"+nf.format(amount);
            userAccountHistory.setActHistoryType(AccountHistoryType.INTEGRAL.getValue());
        }
        userAccountHistory.setVersion(userAccount.getVersion());
        userAccountHistory.setCreateUserId(createUserId);
        userAccountHistory.setDescription(description);
        this.save(userAccountHistory);
        if(order !=null && AccountHistoryType.REFUND.getValue().equals(userAccountHistory.getActHistoryType())){//退费
            userAccountHistory.setOrderNo(order.getOrderNo());
            Map<BigDecimal,List> dataListMap = new HashMap<>();
            dataListMap.put(userAccount.getUserId(),Arrays.asList(userAccountHistory));
            sendMessage.sendMessage(WXTmpEnum.REFUND, Arrays.asList(userAccount.getUserId()),dataListMap);
        }
        return userAccountHistory;
    }

    /**
     * 添加历史记录
     * @param userAccount 账户对象
     * @param trxAmount 操作金额
     * @param accountHistoryType 记录类型
     * @param orderId 订单ID
     * @param orderNo 订单号
     * @param out_trade_no 第三方订单号
     * @param isDisplay 是否前台可显示
     * @param accountBizType 业务类型
     * @param createUserId 管理员名
     */
    public CusUserAccountHistory addHistory(CusUserAccount userAccount, BigDecimal trxAmount, String accountHistoryType,BigDecimal orderId, String orderNo,
                           String out_trade_no, boolean isDisplay, String accountBizType,BigDecimal createUserId){
        CusUserAccountHistory userAccountHistory = new CusUserAccountHistory();
        userAccountHistory.setUserId(userAccount.getUserId());
        userAccountHistory.setOrderId(orderId);
        userAccountHistory.setOrderNo(orderNo);
        userAccountHistory.setOutTradeNo(out_trade_no);
        userAccountHistory.setAccountId(userAccount.getId());
        if(isDisplay){
            userAccountHistory.setIsDisplay(0);
        }else{
            userAccountHistory.setIsDisplay(1);
        }
        userAccountHistory.setBalance(userAccount.getBalance());
        userAccountHistory.setCashAmount(userAccount.getCashAmount());
        userAccountHistory.setCashForzenAmount(userAccount.getCashForzenAmount());
        userAccountHistory.setVmAmount(userAccount.getVmAmount());
        userAccountHistory.setVmForzenAmount(userAccount.getVmForzenAmount());
        userAccountHistory.setTrxAmount(trxAmount);
        String strTrxAmount = this.formatNumber(trxAmount,2);
                /*1.SALES, // 消费，出账  2.REFUND, // 退款
                3.CASHLOAD,//现金充值 4.VMLOAD,//课程卡充值
                5.ADMINLOAD,//后台充值 6.ADMINREFUND,//后台扣款
                7.FORZEN_AMOUNT,//后台冻结 8.THAW_AMOUNT,//后台解冻 9.ATTEND;//问题围观收益*/
        if(accountHistoryType.equals(AccountHistoryType.CASHLOAD.getValue())){
            userAccountHistory.setDescription("现金充值:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.SALES.getValue())){
            userAccountHistory.setDescription("消费金额:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.VMLOAD.getValue())){
            userAccountHistory.setDescription("充值卡充值:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.REFUND.getValue())){
            userAccountHistory.setDescription("退款金额:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.ATTEND.getValue())){
            userAccountHistory.setDescription("问题围观收益:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.SPREAD.getValue())){
            userAccountHistory.setDescription("推广收益:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.REWARD.getValue())){
            userAccountHistory.setDescription("奖金收益:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.CASH.getValue())){
            userAccountHistory.setDescription("提现:"+strTrxAmount);
        }else if(accountHistoryType.equals(AccountHistoryType.REFUND_CASH.getValue())){
            userAccountHistory.setDescription("回退提现:"+strTrxAmount);
        }
        userAccountHistory.setActHistoryType(accountHistoryType);
        userAccountHistory.setBizType(accountBizType);
        userAccountHistory.setVersion(userAccount.getVersion());
        userAccountHistory.setCreateUserId(createUserId);
        this.save(userAccountHistory);

        if(AccountHistoryType.REFUND.getValue().equals(accountHistoryType)){//退费
            Map<BigDecimal,List> dataListMap = new HashMap<>();
            dataListMap.put(userAccount.getUserId(),Arrays.asList(userAccountHistory));
            sendMessage.sendMessage(WXTmpEnum.REFUND, Arrays.asList(userAccount.getUserId()),dataListMap);
        }else if(AccountHistoryType.CASH.getValue().equals(accountHistoryType)){//提现
            Map<BigDecimal,List> dataListMap = new HashMap<>();
            dataListMap.put(userAccount.getUserId(),Arrays.asList(userAccountHistory));
            sendMessage.sendMessage(WXTmpEnum.CASH, Arrays.asList(userAccount.getUserId()),dataListMap);
        }
        return userAccountHistory;
    }


    /**
     * 查询用户账户消费记录列表
     * @param userAccountHistoryColumns 查询条件
     * @param page 分页条件
     * @return List<UserAccountHistory> 消费记录列表
     */
    public PageInfo<CusUserAccountHistory> queryUserAccountHistoryListPage(CusUserAccountHistoryColumns userAccountHistoryColumns, Pagination page,boolean createUserData ){
       String whereSql = this.whereSql(userAccountHistoryColumns);
       PageInfo<CusUserAccountHistory> pageInfo = this.findPage(whereSql,page,new ArrayList<>());
       //处理合并ios内购充值
        if(ObjectUtils.isNotEmpty(pageInfo.getList())&&pageInfo.getList().size()>0){
            pageInfo.setList( setIosOrder(pageInfo.getList()));
        }
        if (createUserData){
           sysUserBiz.setSysUserData(pageInfo.getList(),createUserData);
       }
        return  pageInfo;
    }

    /**
     *
     * 合并ios订单
     * @param list
     * @return
     */
    private  List<CusUserAccountHistory> setIosOrder( List<CusUserAccountHistory> list){
        for ( CusUserAccountHistory items : list) {
            for ( CusUserAccountHistory item : list) {
                if(StringUtils.isNotEmpty(items.getOrderNo())&&StringUtils.isNotEmpty(item.getOrderNo())&&items.getOrderNo().equals(item.getOrderNo())&&items.getId().compareTo(item.getId())!=0) {
                    items.setTrxAmount(items.getTrxAmount().add(item.getTrxAmount()));
                    list.remove(item);
                    break;
                }
            }
        }
return list;
    }


    /**
     * 查询用户账户历史列表
     * @param userAccountHistoryColumns 查询条件
     * @param createUserData 是否设置创建用户扩展数据
     * @return List<CusUserAccountHistory> 账户历史列表
     */
    public List<CusUserAccountHistory> queryUserAccountHistoryList(CusUserAccountHistoryColumns userAccountHistoryColumns, boolean createUserData ){
        String whereSql = this.whereSql(userAccountHistoryColumns);
        List<CusUserAccountHistory> cusUserAccountHistories =this.find(whereSql,null,new ArrayList<>());
        if (createUserData){
            sysUserBiz.setSysUserData(cusUserAccountHistories,createUserData);
        }
        return  cusUserAccountHistories;
    }

    /**
     * 获取Sql语句
     * @param cusUserAccountHistoryColumns
     * @return
     */
    public String whereSql(CusUserAccountHistoryColumns cusUserAccountHistoryColumns){
        StringBuilder whereSql = new StringBuilder(" 1=1 ");
        if (ObjectUtils.isNotEmpty(cusUserAccountHistoryColumns)) {
            if (DataUtil.idIsNotNull(cusUserAccountHistoryColumns.getUserId())){
                whereSql .append( " and userId=").append(cusUserAccountHistoryColumns.getUserId());
            }
            if(StringUtils.isNotEmpty(cusUserAccountHistoryColumns.getActHistoryType())){
                whereSql.append(" and actHistoryType='").append(cusUserAccountHistoryColumns.getActHistoryType()).append("'");
            }
            if(StringUtils.isNotEmpty(cusUserAccountHistoryColumns.getDescription())){
                whereSql.append(" and description  like concat('%','" ).append(cusUserAccountHistoryColumns.getDescription() ).append("','%') ");
            }
            if(StringUtils.isNotEmpty(cusUserAccountHistoryColumns.getBizType())){
                whereSql.append(" and bizType='").append(cusUserAccountHistoryColumns.getBizType()).append("'");
            }
            if(StringUtils.isNotEmpty(cusUserAccountHistoryColumns.getOutTradeNo())){
                whereSql.append(" and outTradeNo = '").append(cusUserAccountHistoryColumns.getOutTradeNo()).append("'");
            }
            if(StringUtils.isNotEmpty(cusUserAccountHistoryColumns.getStartTime())){
                whereSql.append(" and createTime >= '").append( cusUserAccountHistoryColumns.getStartTime()).append("'");
            }
            if(StringUtils.isNotEmpty(cusUserAccountHistoryColumns.getEndTime())){
                whereSql.append(" and createTime <= '").append( cusUserAccountHistoryColumns.getEndTime()).append("'");
            }
        }
        if(cusUserAccountHistoryColumns.getOrder()==0){
            whereSql.append(" order by createTime desc");
        }else{
            if(cusUserAccountHistoryColumns.getOrder()==1){
                whereSql.append(" order by actHistoryType desc");
            }else if(cusUserAccountHistoryColumns.getOrder()==2){
                whereSql.append(" order by actHistoryType asc");
            }else if(cusUserAccountHistoryColumns.getOrder()==3){
                whereSql.append(" order by createTime desc");
            }else if(cusUserAccountHistoryColumns.getOrder()==4){
                whereSql.append(" order by createTime asc");
            }
        }
        return whereSql.toString();
    }

    private  String formatNumber(Object o, Integer precision) {
        if (o == null) {
            return "";
        } else {
            DecimalFormat df = null;
            try {
                switch(precision) {
                    case 0:
                        df = new DecimalFormat("#######");
                        break;
                    case 1:
                        df = new DecimalFormat("#######.#");
                        break;
                    case 2:
                        df = new DecimalFormat("#######.##");
                        break;
                    case 3:
                        df = new DecimalFormat("#######.###");
                        break;
                    default:
                        df = new DecimalFormat("#######.##");
                }
                return df.format(Double.parseDouble(o.toString()) + 1.0E-8D);
            } catch (Exception var4) {
                return "0";
            }
        }
    }
}
